
$(document).ready(
	function(){
		initTraining();
	}		
);

function replaceAll(string, token, newtoken) {

	return string.replace(new RegExp(token, 'g'),newtoken);
	
};

function initTraining() {

	var $workoutComposites = $(".workoutComposite"); 
	$workoutComposites.each(function(index, workoutComposite) {
		var id = workoutComposite.id;

		$(workoutComposite).find( ".ui-sortable-custom" ).sortable({
			
			
			placeholder: 'ui-state-hover',
			items: '.ui-stepPanel',
			connectWith: '.ui-sortable-custom',
			forceHelperSize: 'true',
			forcePlaceholderSize: 'true',
		   	tolerance:'pointer',
		   	dropOnEmpty: 'true',
		   	stop: function(event, ui) { 
	   			var parentId = ui.item.closest(".ui-training").attr('id');
	   			var parentStep = ui.item.parent().closest(".ui-panel").find(".ui-step-uuid:first").text();
	   			var childrenStep = ui.item.find(".ui-step-uuid:first").text();
	   			var position = ui.item.index();
	   			var function_name = "tSChanged_" + replaceAll(id,'-|:','_');
   				
	   			if (typeof(window[function_name]) === "function")
	   			{
	   			    window[function_name]([	{name: "parentStep", value: parentStep},
			   			                    {name: "childrenStep", value: childrenStep},
			   			                    {name: "position", value: position},
			   			                    {name: "parentId", value: parentId}
	   			    					]);
	   			}
	   		},
		});
		

		$(workoutComposite).find( ".ui-workout-root" ).disableSelection();
	
		$(workoutComposite).find( ".ui-sortable-custom" ).droppable({
			greedy:'true',
	   });			 			    
	});
}